package x.y.z;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCode_0051 {
    private final List<List<String>> result = new ArrayList<>();

    public List<List<String>> solveNQueens(int n) {
        char[][] board = new char[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(board[i], '.');
        }
        backtrack(board, 0);
        return result;
    }

    private void backtrack(char[][] board, int row) {
        if (board.length == row) {
            addSolutionToResult(board);
        }
        for (int col = 0; col < board[0].length; col++) {
            if (!isValid(board, row, col)) {
                continue;
            }
            board[row][col] = 'Q';
            backtrack(board, row + 1);
            board[row][col] = '.';
        }
    }

    private void addSolutionToResult(char[][] board) {
        List<String> track = new ArrayList<>();
        for (char[] chars : board) {
            track.add(String.valueOf(chars));
        }
        result.add(track);
    }

    private boolean isValid(char[][] board, int row, int col) {
        // 检查列
        for (int j = 0; j < row; j++) {
            if (board[j][col] == 'Q') {
                return false;
            }
        }
        // 检查/对角线
        for (int i = row - 1, j = col + 1; i >= 0 && j < board.length; i--, j++) {
            if (board[i][j] == 'Q') {
                return false;
            }
        }
        // 检查\对角线
        for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }
}
